package services

import "goetl/models"
import "github.com/astaxie/beego/orm"

//用户操作相关
type operationsService struct{}

/*根据登陆ID取得用户信息*/
func (this *operationsService) FindUserByLoginId(login_id string) (err error, loginUser models.User) {

	o := orm.NewOrm()

	user := new(models.User)
	qs := o.QueryTable(user)
	_, err = qs.Filter("LoginId", login_id).RelatedSel().All(&loginUser)

	_, err = o.LoadRelated(&loginUser, "UserSettings")
	return

}

//取得所有agent
func (this *operationsService) FindAgents() (err error, result []*models.Agent) {

	o := orm.NewOrm()

	agent := new(models.Agent)
	qs := o.QueryTable(agent)

	_, err = qs.Filter("Deleted", 0).All(&result)

	if err == nil {
		for i := range result {
			entity := result[i]
			o.LoadRelated(entity, "AgentDeployments")
		}
	}

	return
}

func (this *operationsService) FindAgentsByName(name string) (err error, result []*models.Agent) {
	o := orm.NewOrm()

	agent := new(models.Agent)
	qs := o.QueryTable(agent)

	_, err = qs.Filter("Name", name).Filter("Deleted", 0).All(&result)

	if err == nil {
		for i := range result {
			entity := result[i]
			o.LoadRelated(entity, "AgentDeployments")
		}
	}

	return
}

func (this *operationsService) GetAgentDeploymentFor(agent models.Agent, flow models.Flow) (err error, deploy models.AgentDeployment) {

	o := orm.NewOrm()

	agentDeployment := new(models.AgentDeployment)
	qs := o.QueryTable(agentDeployment)

	qs.Filter("AgentId", agent).Filter("FlowId", flow).One(&deploy)
	o.LoadRelated(&deploy, "AgentId")

	return
}
